package com.rogchen.security.securitycustomuser.configuration;

import com.rogchen.security.securitycustomuser.entity.SysPermission;
import com.rogchen.security.securitycustomuser.entity.SysRole;
import com.rogchen.security.securitycustomuser.entity.SysUser;
import com.rogchen.security.securitycustomuser.service.UserService;
import com.rogchen.security.securitycustomuser.vo.SysUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Rogchen rogchen128@gmail.com
 * @description:
 * @product: IntelliJ IDEA
 * @created Date: 19-11-6 14:27
 **/
@Component
public class CustomUserService implements UserDetailsService {
    @Autowired
    private UserService userService;

    public SysUserVo loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = userService.selectByUsername(username);
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (SysRole role : sysUser.getRoleList()) {
            for (SysPermission permission : role.getPermissionList()) {
                authorities.add(new SimpleGrantedAuthority(permission.getUrl()));
            }
        }
        return new SysUserVo(sysUser.getUsername(), sysUser.getPassword(), authorities);
    }

}
